package com.bw.controller.information;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.entity.information.PiCustomer;
import com.bw.entity.information.PiMaterial;
import com.bw.resp.ResponseResult;
import com.bw.service.information.IPiCustomerService;
import com.bw.service.information.IPiLinkmanService;
import com.bw.utils.excel.ExcelUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import net.sf.excelutils.ExcelException;
import net.sf.excelutils.ExcelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lizhengqian
 * @since 2020-06-15
 */
@RestController
@RequestMapping("/information/pi-customer")
public class PiCustomerController {
    @Autowired
    private IPiCustomerService iPiCustomerService;
    @Autowired
    private IPiLinkmanService iPiLinkmanService;

    private final Logger logger= LoggerFactory.getLogger(PiMaterialController.class);//日志
    @PostMapping("/list/{page}/{num}")
    //列表查询参数1：实体类对象。参数2：每页条数。参数3：开始页数
    public ResponseResult findList(@RequestBody PiCustomer piCustomer, @PathVariable int page,@PathVariable int num)throws Exception{
        logger.info("开始进行客户列表查询");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            QueryWrapper wrapper = new QueryWrapper();
            logger.info("开启分页");
            PageHelper.startPage(num,page);//开启分页
            /*
            * 判断查询条件非空进行查询
            * */
            if(piCustomer.getCode()!=null){//编号非空
                wrapper.eq("code",piCustomer.getCode());
            }
            if(piCustomer.getName()!=null && !"".equals(piCustomer.getName().trim())){//判断名称非null，以及去掉空格后非“”
                wrapper.like("name",piCustomer.getName());
            }
            if(piCustomer.getAddress()!=null){//地址非空
                wrapper.eq("address",piCustomer.getAddress());
            }
            wrapper.eq("isdelete",1);//判断删除标识
            List list = iPiCustomerService.list(wrapper);//根据条件查询出来内容
            PageInfo pageInfo = new PageInfo<>(list);//将查询内容存到分页内容中
            logger.debug("查出所有内容，存入返回集");
            result.setResult(pageInfo);//存入result
        }catch (Exception e){
            logger.error("查询客户列表失败");
            result.setMessage("查询列表失败"+e.toString());
            result.setSuccess(false);
        }
        return result;
    }
    @PostMapping("/cxCotumer/{id}")
    public ResponseResult cxCotumer(@PathVariable int id){//回显 参数1：定义一个接前端传值的对象
        logger.info("客户回显");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            PiCustomer piCustomer = iPiCustomerService.getById(id);//根据获得到的id获取要回显的内容
            logger.debug("查出客户明细内容，存入返回集");
            result.setResult(piCustomer);//存入result
        }catch (Exception e){
            logger.error("查询客户明细失败");
            result.setMessage("查询失败"+e.toString());
            result.setSuccess(false);
        }
        return result;
    }
    @PostMapping("/cxCotumerAll")
    public ResponseResult cxCotumer(@RequestBody PiCustomer piCustomer){//下拉框查询全部 参数1：要获取的参数对象
        logger.info("客户下拉框查询");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            List<PiCustomer> list = iPiCustomerService.list();//查询全部内容
            logger.debug("查出客户下拉框内容，存入返回集");
            result.setResult(list);//存入result
        }catch (Exception e){
            logger.error("查询客户下拉框失败");
            result.setMessage("查询失败"+e.toString());
            result.setSuccess(false);
        }
        return result;
    }
    @PostMapping("/addOrUpdate")
    public ResponseResult addOrUpdate(@RequestBody PiCustomer piCustomer){//添加 参数1：要获取的参数对象
        logger.info("进行客户添加/修改");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            QueryWrapper wrapper = new QueryWrapper();//mybatis plus对象
            /*
            * //根据除传回的编号查询
            * */
            wrapper.eq("code",piCustomer.getCode());
            List list = iPiCustomerService.list(wrapper);
            logger.trace("判断编号唯一");
            if(list.size()>0){
                logger.error("编号重复，添加失败");
                result.setSuccess(false);
                result.setMessage("编号重复,请重新输入");//如果编号重复，发出提示
            }else{
                logger.info("添加成功");
                piCustomer.setIsdelete(1);//默认删除为1（非删除标识）
                iPiCustomerService.saveOrUpdate(piCustomer);//不重复进行添加
                result.setMessage("操作成功");
            }
        }catch (Exception e){
            logger.error("添加失败");
            result.setMessage("操作失败"+e.toString());
            result.setSuccess(false);
        }
        return result;
    }
    @DeleteMapping("/del/{ids}")
    public ResponseResult del(@PathVariable List<Integer> ids){//删除 参数1：定义数组获取前端传回的id数组
        ResponseResult result = ResponseResult.SUCCESS();
        logger.info("客户信息删除功能");
        try {
            logger.debug("循环删除id的数组");
            for (int id:ids) {//循环
                PiCustomer piCustomer = iPiCustomerService.getById(id);
                piCustomer.setIsdelete(0); //根据所获取的id进行循环删除(改变删除标识)
                iPiCustomerService.saveOrUpdate(piCustomer);//重新添加
            }
            result.setMessage("删除成功");
        }catch (Exception e){
            logger.error("删除失败");
            result.setMessage("删除失败"+e.toString());
            result.setSuccess(false);
        }
        return result;
    }
    @GetMapping("/detailById/{id}")
    public ResponseResult detailById(@PathVariable long id){//查看明细 参数1：定义一个接前端传值的对象
        ResponseResult result = ResponseResult.SUCCESS();
        logger.info("客户明细功能");
        try {
            PiCustomer piCustomer = iPiCustomerService.getById(id);//根据获得到的id获取要回显的内容
            result.setMessage("查看成功");//发出提示
            result.setResult(piCustomer);
            logger.debug("查出客户明细内容，存入返回集");
        }catch (Exception e){
            logger.error("查询客户明细失败");
            result.setMessage("查看失败"+e.toString());
            result.setSuccess(false);
        }
        return result;
    }
    @GetMapping("/detailLinkmanById/{id}")
    public ResponseResult detailLinkmanById(@PathVariable long id){//根据客户查看名下的联系人明细 参数1：定义一个接前端传值的对象
        ResponseResult result = ResponseResult.SUCCESS();
        logger.info("查看客户名下联系人明细功能");
        try {
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("customerId",id);
            List list = iPiLinkmanService.list(wrapper);//根据获得到的id获取要回显的内容
            logger.debug("根据客户id查出联系人明细内容，存入返回集");
            result.setMessage("查看成功");
            result.setResult(list);
        }catch (Exception e){
            logger.error("查询联系人明细失败");
            result.setMessage("查看失败"+e.toString());
            result.setSuccess(false);
        }
        return result;
    }
    @GetMapping("/exportExcel")
    public void exportExcel(HttpServletResponse response) throws IOException, ExcelException {//导出  参数1：对浏览器进行操作的response
        List<PiCustomer> list = iPiCustomerService.list();

        /*
        * 定义导出的xls的格式
        * */
        logger.info("导出的xls");
        response.setHeader("Content-Type","application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Content-Disposition","attachment;filename="+new String("用户数据".getBytes(),"iso-8859-1")+".xls");
        ClassPathResource classPathResource = new ClassPathResource("xls/customer.xls");//指向模板
        InputStream inputStream = classPathResource.getInputStream();//获取excel的模板

        ExcelUtils.addValue("list",list);//存入数据
        logger.info("向模板存值");

        ExcelUtils.export(inputStream,ExcelUtils.getContext(),response.getOutputStream());//第一个参数：模板的流。第三个：输出到哪
        logger.info("输出Excel");

    }
    @PostMapping("/importExcel")
    public ResponseResult importExcel(MultipartFile file){//导入 参数1：文件流
        logger.info("导入的xls");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            String ext = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."), file.getOriginalFilename().length());//获取后缀
            List<Map> mapList = ExcelUtil.readExcel(ext, file.getInputStream());//根据工具类读取到Excel所有内容
            logger.info("读取到Excel所有内容");
            String jsonString = JSON.toJSONString(mapList);//转为String类型
            List<PiCustomer> list = JSON.parseArray(jsonString, PiCustomer.class);//转为JSON格式
            logger.info("全部内容转为JSON格式");
            iPiCustomerService.saveBatch(list);//批量添加
            logger.info("批量添加到数据库");
        }catch (Exception e){
            logger.error("导入失败"+e.toString());
            result.setMessage("导入失败"+e.toString());
            result.setSuccess(false);
        }
        return result;
    }
    @PostMapping("/getCustomerNum")
    /**
     * @MethodName 客户发票
     * @Author Yang955
     * @param: customerId
     * @UpdateTime 2020/6/26 13:57 com.bw.resp.ResponseResult
     * @Return com.bw.resp.ResponseResult
     */
    public ResponseResult getCustomerNum(){
        logger.info("执行客户端订单数据统计");
        ResponseResult result = ResponseResult.SUCCESS();

        try {
            QueryWrapper queryWrapper = new QueryWrapper();


            List<Map> list = iPiCustomerService.getCustomerNum();

            Map<String,Map> listInfo = new HashMap<>();

            List num  = new ArrayList();
            List customerName  = new ArrayList();
            for (int i=0;i<list.size();i++){
                num.add(list.get(i).get("count(*)"));
                customerName.add(list.get(i).get("customerName"));
            }
            Map<String,List> numMap = new HashMap();
            numMap.put("num",num);
            numMap.put("customerName",customerName);
            /*Map<String,List> customerMap = new HashMap();
            numMap.put("customerName",customerName);*/
            listInfo.put("customerStat",numMap);
            //listInfo.add(customerMap);

            System.out.println("客户端订单数据统计："+listInfo);
            result.setResult(listInfo);
            result.setSuccess(true);
            result.setMessage("查找已支付订单成功！");
            logger.info("客户端订单数据统计成功");
        }catch (Exception e){
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage("发送失败！");
            logger.info("客户端订单数据统计失败");
        }
        return result;
    }


    @PostMapping("/getTechnologyNum")
    /**
     * @MethodName 工艺数据统计
     * @Author Yang955
     * @param: customerId
     * @UpdateTime 2020/6/26 13:57 com.bw.resp.ResponseResult
     * @Return com.bw.resp.ResponseResult
     */
    public ResponseResult getTechnologyNum(){
        logger.info("执行工艺数据统计");
        ResponseResult result = ResponseResult.SUCCESS();

        try {
            QueryWrapper queryWrapper = new QueryWrapper();
            List<Map> list = iPiCustomerService.getTechnologyNum();

            System.out.println("工艺数据统计："+list);
            result.setResult(list);
            result.setSuccess(true);
            logger.info("工艺统计成功");
        }catch (Exception e){
            e.printStackTrace();
            result.setSuccess(false);
            logger.info("工艺统计失败");
        }
        return result;
    }

}
